package cz.vse.javaee.email;

import java.io.IOException;
import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author  VERNER Jan
 * @version 16.3.2012
 */
public class MailServlet extends HttpServlet
{
//== CONSTANTS & FIELDS (STATIC) ===============================================
//== CONSTANTS & FIELDS ========================================================
    
    @Resource(name="mail/myMailSession")
    private Session mailSession;
    
    // path (folder) where email concepts are stored
    private String conceptPath;
    

//== CONSTRUCTORS (STATIC) =====================================================
//== CONSTRUCTORS AND FACTORY METHODS ==========================================

//== NON-PRIVATE METHODS (STATIC) ==============================================
//== NON-PRIVATE METHODS =======================================================
    
    @Override
    public void init(ServletConfig config) {
        this.conceptPath = config.getInitParameter("conceptPath");
    }
    
    @Override
    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response)
            throws ServletException, IOException
    {
        // Při HTTP metodě POST se očekává, že je v session
        // k dispozici e-mail bean.
        EmailBean emailBean = (EmailBean)
                request.getSession().getAttribute("emailBean");
        if (emailBean == null) {
            throw new ServletException("No email session");
        }
        
        try {
            EmailAction action = EmailAction.valueOf(
                    request.getParameter("action").toUpperCase()); 
            
            switch (action)
            {
                case SEND:
                    doSend(emailBean, request, response);       break;
                case NEW:
                    createEmailBean(request, response);         break;
                case STORE:
                    doStore(emailBean, request, response);      break;
                case RESTORE:
                    doRestore(emailBean, request, response);    break;
            }              
        } catch (IllegalArgumentException ex) {
            throw new ServletException("No action specified!", ex);
        } catch (Exception ex) {
            throw new ServletException(ex);
        }
    }
    
    @Override
    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response)
            throws ServletException, IOException
    {
        // Lazy inicializace email beanu
        EmailBean emailBean = (EmailBean)
                request.getSession().getAttribute("emailBean");
        if (emailBean == null) {
            // email bean není v session, vytvoříme jej tedy
            createEmailBean(request, response);
        }
        else {
            // Pokud je email bean v session, přesměrováváme na emailForm.jsp.
            response.sendRedirect("mailForm.jsp");
        }
    }
    
    
//== PRIVATE METHODS (STATIC) ==================================================
//== PRIVATE METHODS ===========================================================
     
    /**
     * Akce, která vytvoří nový e-mail bean a vloží jej
     * do session jako atribut.
     */
    private void createEmailBean(HttpServletRequest request,
                                 HttpServletResponse response)
            throws IOException
    {
        EmailBean emailBean = new EmailBean();
        request.getSession().setAttribute("emailBean", emailBean);
        
        // přesměrujeme na formulář
        response.sendRedirect("mailForm.jsp");
    }
    
    /**
     * Akce, která odesílá email voláním business metody
     * na email beanu.
     */
    private void doSend(EmailBean emailBean,
                        HttpServletRequest request,
                        HttpServletResponse response)
            throws IOException, MessagingException, ServletException
    {
        // naplníme beanu aktuálními hodnotami
        prepareBean(emailBean, request);

        // odešleme email
        emailBean.send(mailSession);

        // přesměrujeme na resumé
        response.sendRedirect("resume.jsp");
    }
    
    private void doStore(EmailBean emailBean,
                        HttpServletRequest request,
                        HttpServletResponse response)
            throws IOException, ServletException
    {
        // naplníme beanu aktuálními hodnotami
        prepareBean(emailBean, request);
        
        // uložíme rozepsaný email
        emailBean.store(conceptPath);
        
        // Získáme dispečera stránky
        RequestDispatcher loginDispatcher =
                request.getRequestDispatcher("mailForm.jsp"); // ?? vs. sendRedirect
        loginDispatcher.forward(request, response);
    }
    
    private void doRestore(EmailBean emailBean,
                        HttpServletRequest request,
                        HttpServletResponse response)
            throws IOException, ServletException
    {
        emailBean.restore(conceptPath, emailBean);
                // Získáme dispečera stránky
        RequestDispatcher loginDispatcher =
                request.getRequestDispatcher("mailForm.jsp"); // ?? vs. sendRedirect
        loginDispatcher.forward(request, response);
    }
    
    private void prepareBean(EmailBean emailBean, HttpServletRequest request)
    {
        // Přečteme si parametry z formuláře
        String to       = request.getParameter("to");
        String subject  = request.getParameter("subject");
        String message  = request.getParameter("message");
        
        System.out.println("TO: " + to);

        // Nastavíme vlastnosti e-mail beanu
        emailBean.setTo(to);
        emailBean.setSubject(subject);
        emailBean.setBody(message);
    }

    
//== NESTED TYPES ==============================================================

//== MAIN METHOD (TEST) ========================================================
    
//    /**
//     * @param args the command line arguments
//     */
//    public static void main(String[] args) {
//        // TODO code application logic here
//    }

}
